package cn.yanghan.org.service.impl;

import cn.yanghan.org.domain.Department;
import cn.yanghan.org.mapper.DepartmentMapper;
import cn.yanghan.org.query.DepartmentQuery;
import cn.yanghan.org.service.IDepartmentService;
import cn.yanghan.org.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        //dirPath 维护
        //1.判断上级parent 是否为空
        if(department.getParent()==null){
            department.setDirPath("/"+department.getId());
        }else{
            //获取上级部门的dirPath
            Department parent = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(parent.getDirPath()+"/"+department.getId());
        }

        //跟新数据
        departmentMapper.update(department);
    }

    @Override
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    public void update(Department department) {

        //dirPath 维护
        //1.判断上级parent 是否为空
        if(department.getParent()==null){
            department.setDirPath("/"+department.getId());
        }else{
            //获取上级部门的dirPath
            Department parent = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(parent.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);

    }

    @Override
    public Department loadById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public List<Department> loadAll() {
        return departmentMapper.loadAll();
    }

    @Override
    public QueryResult<Department> queryPage(DepartmentQuery query) {
        Long count = departmentMapper.queryCount(query);
        List<Department> data = departmentMapper.queryData(query);
        return new QueryResult<>(count,data);
    }

    @Override
    @Transactional
    public void patchDel(Long[] ids) {
        departmentMapper.patchDel(ids);
    }

    @Override
    public List<Department> loadDeptTree() {
        return departmentMapper.loadDeptTree();
    }
}
